package cn.caidabao.gb.component.media;

import cn.caidabao.gb.bean.MediaResponse;
import cn.caidabao.gb.component.media.MediaApi;
import cn.caidabao.gb.config.ZLMConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.Proxy;

@Slf4j
@Component
public class ZLMMediaApi implements MediaApi {
    @Resource
    private ZLMConfig zlmConfig;
    @Override
    public MediaResponse openRtpServer(String channelId) throws IOException {
        HttpUrl url = HttpUrl.parse("http://"+zlmConfig.getIp()+":"+zlmConfig.getApiPort()+"/index/api/openRtpServer").newBuilder()
                .addQueryParameter("secret", zlmConfig.getSecret())  // 参数1
                .addQueryParameter("port", "0")// 参数2
                .addQueryParameter("tcp_mode","1")
                .addQueryParameter("stream_id",channelId)
                .build();
        Request request = new Request.Builder()
                .url(url)// 目标 URL
                .addHeader("User-Agent","Only-GB-Sip")
                .build();
        Response response = new OkHttpClient.Builder().proxy(Proxy.NO_PROXY).build().newCall(request).execute();
        JSONObject body = JSON.parseObject(response.body().string());
        MediaResponse mediaResponse = new MediaResponse();
        String code = body.getString("code");
        mediaResponse.setSuccess("0".equals(code));
        mediaResponse.setPort(body.getString("port"));
        mediaResponse.setIp(zlmConfig.getIp());
        mediaResponse.setSsrcId(channelId);
        if (!mediaResponse.isSuccess()){
            mediaResponse.setErrorMsg(body.getString("msg"));
        }
        return mediaResponse;
    }
}
